<template>
  <div style="margin-right: 30px">
    <el-form ref="formObj" :model="wyform" :rules="rules" label-width="100px">
      <el-form-item label="姓名" prop="name">
        <el-input maxLength="20" v-model="wyform.name" placeholder="请输入管理员姓名"></el-input>
      </el-form-item>
	  
      <el-form-item label="性别" prop="sex">
        <el-radio-group v-model="wyform.sex">
          <el-radio :value="1">男</el-radio>
          <el-radio :value="0">女</el-radio>
        </el-radio-group>
      </el-form-item>
	  
	  <el-form-item label="手机号" prop="phone">
        <el-input maxLength="15" v-model="wyform.phone" placeholder="请输入手机号"></el-input>
      </el-form-item>
	  
      <el-form-item label="身份证号" prop="idcard">
	    <el-input maxLength="18" v-model="wyform.idcard" placeholder="请输入身份证号"></el-input>
	  </el-form-item>
	  
      <el-form-item label="电子信箱" prop="email">
        <el-input maxLength="64" v-model="wyform.email" placeholder="请输入电子信箱"></el-input>
      </el-form-item>
	  
	  <el-form-item v-if="!props.id" label="登录密码" prop="password">
        <el-input v-model="wyform.password" placeholder="请输入登录密码" show-password></el-input>
      </el-form-item>
	  
	  <!-- <el-form-item label="身份编号" prop="roleNumber">
	    <el-input v-model="wyform.roleNumber" placeholder="请输入身份编号"></el-input>
	  </el-form-item> -->
	  
	  <div class="form-row">
	    <el-form-item class="form-item" label="省" prop="province">
	  	<el-select v-model="wyform.province" @change="onProvinceChange">
	  	  <el-option v-for="province in provinces" :key="province.code" :label="province.name" :value="province.name"></el-option>
	  	</el-select>
	    </el-form-item>
	    <el-form-item class="form-item" label="市" prop="city">
	  	<el-select v-model="wyform.city" @change="onCityChange">
	  	  <el-option v-for="city in cities" :key="city.code" :label="city.name" :value="city.name"></el-option>
	  	</el-select>
	    </el-form-item>
	  </div>
	  <div class="form-row">
	    <el-form-item class="form-item" label="县(区)" prop="county">
	  	<el-select v-model="wyform.county" @change="onCountyChange">
	  	  <el-option v-for="county in counties" :key="county.code" :label="county.name" :value="county.name"></el-option>
	  	</el-select>
	    </el-form-item>
	    <el-form-item class="form-item" label="乡(镇)" prop="township">
	  	<el-select v-model="wyform.township" @change="onTownshipChange">
	  	  <el-option v-for="township in townships" :key="township.code" :label="township.name" :value="township.name"></el-option>
	  	</el-select>
	    </el-form-item>
	  </div>
	  
	  <el-form-item label="头像" prop="file">
			<div style="width: 150px; height: 150px; overflow: hidden;">
				<el-upload
					list-type="picture-card"
					:auto-upload="false"
					action="#"
					:limit="1"
					:on-change="uploadFile"
					:on-remove="removeFile"
					v-model:file-list="fileList">
					<el-icon><PictureFilled /></el-icon>
				</el-upload>
			</div>
	  </el-form-item>
	  
      <el-form-item>
        <el-button type="primary" plain :icon="Save" @click="save">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import areaData from '@/area/pcas-code.json'
import Save from '@/components/icons/lssave'
import { ref,onMounted ,watch,reactive } from 'vue'
import { get, post } from '@/axios'
import url from './util'
import { getPath } from '@/util'
import { PictureFilled } from '@element-plus/icons-vue'
const emits = defineEmits(['update:show', 'getTableData'])
const props = defineProps(['id'])
const fileList = reactive([])
const wyform = reactive({
	id: null,
  name: '',
  idcard:'',
  sex: null,
  phone: '',
  email: '',
  password: '',
  province: '',
  city: '',
  county: '',
  township: '',
  areaId:'',
  file: ''
})
const provinces = ref([]);
const cities = ref([]);
const counties = ref([]);
const townships = ref([]);

const rules = reactive({
	name: [
		{ required: true, message: '请输入管理员姓名', trigger: 'blur' }
	],
	// roleNumber: [
	// 	{ required: true, message: '请输入管理员角色', trigger: 'blur' }
	// ],
	// sex: [
	// 	{ required: true, message: '请选择管理员性别', trigger: 'blur' }
	// ],
	// areaId: [
	// 	{ required: true, message: '请输入管理员地区编码', trigger: 'blur' }
	// ],
	// phone: [
	// 	{ required: true, message: '请输入手机号码', trigger: 'blur' },
	// 	{ pattern: /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/, message: '请输入正确的中国手机号', trigger: 'blur' },
	// 	{ validator: check, message: '该手机号已经被使用', trigger: 'blur' }
	// ],
	// email: [
	// 	{ required: true, message: '请输入电子信箱', trigger: 'blur' },
	// 	{ type: 'email', message: '请输入正确的电子信箱', trigger: 'blur' },
	// 	{ validator: check, message: '该电子信箱已经被使用', trigger: 'blur' }
	// ],
	// password: [
	// 	{ required: true, message: '请输入登录密码', trigger: 'blur' }
	// ],
	// idcard: [
	// 	{ required: true, message: '请输入身份账号', trigger: 'blur' },
	// 	{ pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: '请输入正确的身份证号', trigger: 'blur' },
	// 	{ validator: check, message: '该身份证号已经被使用', trigger: 'blur' }
	// ],
	// file: [
	// 	{ required: props.id === null, message: '请上传管理员头像', trigger: 'blur' }
	// ]
})
const formObj = ref()
if (props.id) {
	wyform.id = props.id
	getById()
}
function check (rule, value, callback) {
	get(url.check, { id: props.id, value, field: rule.field }, content => {
		if (content) {
			callback()
		} else {
			callback(new Error())
		}
	})
}
function save() {
	post(props.id ? url.update : url.add, wyform, content => {
		emits('update:show', false)
		emits('getTableData')
	}, formObj)
}
function getById () {
	get(url.getById, { id: props.id }, content => {
		console.dir(content)
		for (const key in wyform) {
			if (Object.prototype.hasOwnProperty.call(content, key)) {
				wyform[key] = content[key]
			}
		}
		fileList.push({ url: getPath(content.icon) })
		if (wyform.province) {
		    // 初始化市级数据
		    const selectedProvince = provinces.value.find(province => province.name === wyform.province);
		    if (selectedProvince) {
		      cities.value = selectedProvince.cities.map(city => ({
		        name: city.name,
		        code: city.code,
		        counties: city.children || [],
		      }));
		    }
		
		    if (wyform.city) {
		      // 初始化县级数据
		      const selectedCity = cities.value.find(city => city.name === wyform.city);
		      if (selectedCity) {
		        counties.value = selectedCity.counties.map(county => ({
		          name: county.name,
		          code: county.code,
		          townships: county.children || [],
		        }));
		      }
		
		      if (wyform.county) {
		        // 初始化乡级数据
		        const selectedCounty = counties.value.find(county => county.name === wyform.county);
		        if (selectedCounty) {
		          townships.value = selectedCounty.townships.map(township => ({
		            name: township.name,
		            code: township.code,
		          }));
		        }
		      }
		    }
		  }
	})
}
function uploadFile (file) {
	wyform.file = file.raw
}
function removeFile () {
	wyform.file = null
}

onMounted(() => {
  provinces.value = areaData.map(province => ({
    name: province.name,
    code: province.code,
    cities: province.children || [],
  }));
});

// 选择省份后加载市
const onProvinceChange = (value) => {
  wyform.province = value;
  wyform.city = '';
  wyform.county = '';
  wyform.township = '';
  
  const selectedProvince = provinces.value.find(province => province.name === value);

  if (selectedProvince) {
    cities.value = selectedProvince.cities.map(city => ({
      name: city.name,
      code: city.code,
      counties: city.children || [],
    }));
  } else {
    cities.value = [];
  }

  counties.value = [];
  townships.value = [];
  wyform.areaId = selectedProvince.code;
};

// 选择市后加载县
const onCityChange = (value) => {
  wyform.city = value;
  wyform.county = '';
  wyform.township = '';

  const selectedCity = cities.value.find(city => city.name === value);

  if (selectedCity) {
    counties.value = selectedCity.counties.map(county => ({
      name: county.name,
      code: county.code,
      townships: county.children || [],
    }));
  } else {
    counties.value = [];
  }

  townships.value = [];
  wyform.areaId = selectedCity.code;
};

// 选择县后加载乡
const onCountyChange = (value) => {
  wyform.county = value;
  wyform.township = '';

  const selectedCounty = counties.value.find(county => county.name === value);

  if (selectedCounty) {
    townships.value = selectedCounty.townships.map(township => ({
      name: township.name,
      code: township.code,
    }));
  } else {
    townships.value = [];
  }
  wyform.areaId = selectedCounty.code;
};

// 选择乡镇后绑定 rId
const onTownshipChange = (value) => {
  wyform.township = value;
  const townshipData = townships.value.find(township => township.name === value);
  wyform.areaId = townshipData ? townshipData.code : null;
};
</script>

<style scoped lang="scss"></style>
